<?php

namespace app\console\controller;

namespace app\console\controller;
use lib\Page;
use app\console\model\ShopAssignorRecords;
use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\ShopAssignor as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;

class ShopAssignor extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'clearCache' => ['only'],
    ];


    /**
     * 广告位列表
     */
    public function index()
    {

        $shop_id = Request::instance()->param('shop_id');
        $keyword = Request::instance()->param('keywords');
		$param = Request::instance()->param();
        $where = [];
        //$shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;
        if(\session('auding_status') == 1){
            $where['shop_id'] = ['eq',\session('shop_id')];
        }else{
            if(!empty($shop_id)) $where['shop_id'] = ['eq',$shop_id];
            if (!empty($keyword)) $where['name'] =['like','%'.$keyword.'%'];
        }



        $data = Model::order(['sort' => 'asc','id' => 'desc'])
            ->where($where)
            ->where('is_delete',1)
            ->paginate(10,false,['query'=>$param])->each(function($item,$key){
                $item->sum_price = Db::name('shop_assignor_records')->where('is_agree',2)->where('assignor_id',$item->id)->sum('assignor_price');
                $item->shop_title = Db::name('shop')->where('id',$item->shop_id)->value('shop_title');

            });

        return $this->fetch('', [
            'data' => $data,

        ]);
    }

    public function daochu(){
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['assignor_id'])) $where['sar.assignor_id'] = ['eq',$param['assignor_id']];
        if(!empty($param['type'])) $where['sar.type'] = ['eq',$param['type']];
        if(!empty($param['is_agree'])) $where['sar.is_agree'] = ['eq',$param['is_agree']];
        if(!empty($param['title'])) $where['o.order_number|gc.card_num'] = ['eq',$param['title']];
        if (!empty($param['shop_id'])) $where['sar.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['card_type'])) $where['o.card_type'] = ['eq', $param['card_type']];

        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['sar.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        if (session('auding_status') == 1) {
            $where['sar.shop_id'] = \session('shop_id');
            $where1['shop_id'] = \session('shop_id');
        } else {

        }
        if (!empty($param['order_type'])) $where['o.order_type'] = ['eq', $param['order_type']];
        $shop_assignor = Db::name('ShopAssignor')->where('shop_id',\session('shop_id'))->select();
        // 2020-6-15---修改
//        $data = Db::name('shop_assignor_records sar')
//            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
//            ->join('order o','sar.order_id = o.id','left')
//            ->join('shop s','sar.shop_id = s.id','left')
//            ->join('gift_card gc','o.order_number = gc.order_number','left')
//            ->field('sar.*,sa.name,o.order_number,s.shop_title,o.car_number,o.amount,o.create_time,sar.create_time sc,gc.card_num,o.card_type')
//            ->order('sar.id','desc')
//            ->where($where)
//            ->where('is_agree',2)
//            ->select()->toArray();

        $data = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
            ->join('order o','sar.order_id = o.id')
            ->join('shop s','sar.shop_id = s.id','left')
            ->join('gift_card gc','o.order_number = gc.order_number','left')
            ->field('sar.*,sa.name,o.order_number,s.shop_title,o.car_number,o.amount,o.create_time,sar.create_time sc,gc.card_num,o.card_type')
            ->order('sar.id','desc')
            ->where($where)
            ->where('is_agree',2)
            ->select()->toArray();
		
        $order_sum = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa', 'sar.assignor_id = sa.id', 'left')
            ->join('order o', 'sar.order_id = o.id')
            ->join('gift_card gc','o.order_number = gc.order_number','left')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id', 'desc')
            ->where($where)
            ->order('sar.order_id')
            ->where('is_agree',2)
            ->sum('assignor_price');
        if(!empty($data)){
            foreach ($data as $k => &$v){
                $v['assignor_content'] = Db::name('single')->where('id',$v['assignor_content'])->value('cat_name');
                if($v['order_type'] == 1){

                    $v['assignor_content'] = Db::name('shop_goods')->where('id',$v['assignor_content'])->value('title');
                }
                if($v['type'] == 1){
                    $v['type'] = '服务提成';
                }
                if($v['type'] == 2){
                    $v['type'] = '销售提成';
                }
                if($v['order_type'] == 1) $v['order_type'] = '商品订单';
                if($v['order_type'] == 3){
                    if($v['card_type'] == 1){
                        $v['order_type'] = '礼包订单(礼包)';
                    }else{
                        $v['order_type'] = '礼包订单(实体卡)';
                    }

                }
                if($v['order_type'] == 2) $v['order_type'] = '服务订单';
                $v['total_sum'] = $order_sum;
                if($v['is_agree'] == 1){
                    $v['is_agree'] = '未同意';
                }else{
                    $v['is_agree'] = '已同意';
                }
            }
        }

        $this->push_coupon($data,'门店人员业绩记录');
        return view('',['shop_assignor' => $shop_assignor,'data' => $data]);
    }

    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '订单ID')
            ->setCellValue('B1', '门店名称')
            ->setCellValue('C1', '订单号')
            ->setCellValue('D1', '订单车牌号')
            ->setCellValue('E1', '订单类型')
            ->setCellValue('F1', '实体卡卡号')
            ->setCellValue('G1', '提成类型')
            ->setCellValue('H1', '服务人员')
            ->setCellValue('I1', '服务金额')
            ->setCellValue('J1', '服务内容')
            ->setCellValue('K1', '服务时间')
            ->setCellValue('L1', '订单总金额')
            ->setCellValue('M1', '是否同意')
            ->setCellValue('N1', '下单时间')
            ->setCellValue('O1', '提成总金额')
        ;
        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['shop_title'])
                ->setCellValue('C' . $num, $v['order_number'])
                ->setCellValue('D' . $num, $v['car_number'])
                ->setCellValue('E' . $num, $v['order_type'])
                ->setCellValue('F' . $num, $v['card_num'])
                ->setCellValue('G' . $num, $v['type'])
                ->setCellValue('H' . $num, $v['name'])
                ->setCellValue('I' . $num, $v['assignor_price'])
                ->setCellValue('J' . $num, $v['assignor_content'])
                ->setCellValue('K' . $num, $v['create_time'])
                ->setCellValue('L' . $num, $v['amount'])
                ->setCellValue('M' . $num, $v['is_agree'])
                ->setCellValue('N' . $num, $v['sc'])
                ->setCellValue('O' . $num, $v['total_sum'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('个人业绩记录');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }



    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            if(empty($data['shop_id'])){
               // fail('请选择门店');
            }
//            // 验证
//            $validate = Loader::validate('AdType');
//            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }


        return $this->fetch('create', [

        ]);

    }


    /**
     * 广告位编辑
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            // 验证
           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);


            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $item = Model::get($id);
        return $this->fetch('create', [
            'item' => $item
        ]);
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
           Db::name('shop_assignor')->where('id',$id)->update(['is_delete'=> 2]);
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }





    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            (new AdTypeModel)->where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('AdType/index'));
    }

    public function records()
    {
        $param = Request::instance()->param();
        $where = [];
        $where1 = [];
        if (!empty($param['assignor_id'])) $where['sar.assignor_id'] = ['eq', $param['assignor_id']];
        if (!empty($param['card_type'])) $where['o.card_type'] = ['eq', $param['card_type']];
        if(!empty($param['is_agree'])) $where['sar.is_agree'] = ['eq',$param['is_agree']];
        if (!empty($param['shop_id'])) $where['sar.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['title'])) $where['o.order_number|gc.card_num'] = ['eq', $param['title']];
        if (!empty($param['type'])) $where['sar.type'] = ['eq', $param['type']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['sar.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }else{
			$six_begin_time = date('Y-m-d 00:00:00',time());
			$six_end_time = date('Y-m-d 23:59:59',time());
			$where['sar.create_time'] = ['between', [$six_begin_time, $six_end_time]];
		}
		
		
        if (session('auding_status') == 1) {
            $where['sar.shop_id'] = \session('shop_id');
            $where1['shop_id'] = \session('shop_id');
        } else {
            if(!empty($param['shop_id'])) $where1['shop_id'] = ['eq',$param['shop_id']];
        }
        if (!empty($param['order_type'])) $where['o.order_type'] = ['eq', $param['order_type']];
        $shop_assignor = Db::name('ShopAssignor')
            ->alias('sa')
            ->join('shop s','sa.shop_id = s.id')
            ->field('sa.*')
//            ->where('s.auding_status',2)
            ->where('s.is_delete',1)
            ->where($where1)
            ->order(['sa.name' => 'desc'])
            ->select();
		$level = Db::name('manager')->where(['id' => session('manage_id'),])->order('id', 'desc')->value('level');
        $data = (new ShopAssignorRecords())
            ->alias('sar')
            ->join('shop s','sar.shop_id = s.id')
            ->join('shop_assignor sa', 'sar.assignor_id = sa.id', 'left')
            ->join('order o', 'sar.order_id = o.id')
			->join('member mm', 'o.member_id = mm.id')
            ->join('gift_card gc','o.order_number = gc.order_number','left')
            ->field('sar.*,sa.name,o.order_number,s.shop_title,o.car_number,o.amount,mm.username,o.create_time,sar.create_time sc,gc.card_num,o.card_type')
            ->order('sar.id', 'desc')
            ->where($where)
            ->paginate(10, false, ['query' => $param])->each(function($item,$key){
                $item->assignor_id = Db::name('single')->where('id',$item->single_id)->value('cat_name');
                $item->assignor_content = Db::name('single')->where('id',$item->assignor_content)->value('cat_name');
				//
				$level = Db::name('manager')->where(['id' => session('manage_id'),])->order('id', 'desc')->value('level');
				//$item->status = Db::name('order')->where('id',$item->order_id)->value('status');
				if($level !='1'){
					$item['username']  =substr_replace($item['username'],'*****',2,5);
					session('shifou_chaoguan', 1);
				}else{
					//$item['username']  =substr_replace($item['username'],'*****',2,5);
					session('shifou_chaoguan', 2);	
				}
				
				
                if($item->is_agree == 1){
                    $item->is_agree = '未同意';
                }else{
                    $item->is_agree = '已同意';
                }

                if($item->order_type == 1){

                    $item->assignor_content = Db::name('shop_goods')->where('id',$item->single_id)->value('title');
                    $goods_id = Db::name('shop_goods')->where('id',$item->single_id)->value('goods_id');
                    $item->assignor_id = Db::name('goods_type')->where('id',$goods_id)->value('title');
                }

                if($item['type'] == 1){
                    $item['type'] = '服务提成';
                }
                if($item['type'] == 2){
                    $item['type'] = '销售提成';
                }
            });
		//var_dump($data);

        $order_count =(new ShopAssignorRecords())
            ->alias('sar')
            ->join('shop_assignor sa', 'sar.assignor_id = sa.id', 'left')
            ->join('order o', 'sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id', 'desc')
            ->join('gift_card gc','o.order_number = gc.order_number','left')
            ->where('is_agree',2)
            ->where($where)
            ->count();

        $order_sum = (new ShopAssignorRecords())
            ->alias('sar')
            ->join('shop_assignor sa', 'sar.assignor_id = sa.id', 'left')
            ->join('order o', 'sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id', 'desc')
            ->where($where)
            ->where('is_agree',2)
            ->join('gift_card gc','o.order_number = gc.order_number','left')

            ->sum('assignor_price');

        $order_id = (new ShopAssignorRecords())
            ->alias('sar')
            ->join('shop_assignor sa', 'sar.assignor_id = sa.id', 'left')
            ->join('order o', 'sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id', 'desc')
            ->where($where)
            ->join('gift_card gc','o.order_number = gc.order_number','left')
            ->where('is_agree',2)

            ->group('sar.order_id')
            ->column('sar.order_id');

        $order_amount = Db::name('order')->where('id','in',$order_id)->sum('amount');

        //halt($data->toArray()['data']);

        return view('', ['shop_assignor' => $shop_assignor,'order_amount' => $order_amount, 'data' => $data, 'order_count' => $order_count, 'order_sum' => $order_sum]);
    }

    public function page()
    {
        $param = Request::instance()->param();
        $total = count(Db::name('shop')->select());
        $listRows = 10;
        $Page = new Page($total, $listRows, $param);
        $list = Db::name('shop')->limit($Page->firstRow . ',' . $listRows)->select();
        $pageHtml = $Page->show(__FUNCTION__);// 分页显示输 __FUNCTION__

        return view('', ['data' => $list, 'pageHtml' => ($pageHtml)]);
    }

    public function abc(){
        $shop_assignor = Db::name('ShopAssignor')
            ->alias('sa')
            ->join('shop s','sa.shop_id = s.id')
            ->field('sa.*')
            ->where('s.auding_status',2)
            ->where('s.is_delete',1)
            ->select();
        return $shop_assignor;
    }

    public function a(){
        //你这个就是一个表里有2个用户id 就得这么差拿到第2个字段的值
        //a表id对应 b表 字段 ps.field_a和filed_b
       $data=  Db::name('a')->join('b','a.id=b.field_a')->select();//得到第一个a字段标题
        if(!empty($datga)){
            foreach ($data as &$v){
                $v['two_field'] = Db::name('a')->where('id',$v['field_b'])->value('title');
            }
        }
    }


    public function shopAssignor($shop_id)
    {
        $where = [];
        if (!empty($shop_id)) $where['sa.shop_id'] = ['eq', $shop_id];
        $data = Db::name('shopAssignor')
            ->alias('sa')
            ->join('shop s', 'sa.shop_id = s.id')
            ->field('sa.*')
            ->where($where)
            ->where('s.auding_status', 2)
            ->where('s.is_delete', 1)
            ->select();
        return $data;
    }

    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}